package insert

import (
	"flag"
	"fmt"
	"jsoninsert/models"
	"log"
	"os"

	_ "github.com/go-sql-driver/mysql"
	"gopkg.in/ini.v1"
)

var configfile string
var cfg *ini.File
var tagType int

func Init() {
	flag.StringVar(&configfile, "c", "config.ini", "config file path")
	flag.Parse()
}

// InitConfig 初始化配置文件
func InitConfig() {
	var err error
	cfg, err = ini.Load(configfile)
	if err != nil {
		log.Println("config file " + configfile + " is not exist...")
		os.Exit(1)
	}
	tagType = cfg.Section("data").Key("tag_type").MustInt()
	log.Println("loading config file " + configfile + " successful")
}

// InitDB 初始化 xorm
func InitDB() {
	section, err := cfg.GetSection("database")
	if err != nil {
		log.Println("get database info error, please check your config file")
		os.Exit(1)
	}
	host := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", section.Key("user").String(), section.Key("pwd").String(), section.Key("host").String(), section.Key("port").String(), section.Key("dbname").String())
	models.InitEngine(host)
}

// InsertData 插入数据
func InsertData() {
	path := cfg.Section("data").Key("filepath").String()
	f := ReadJson(path)
	table := cfg.Section("data").Key("table").MustInt(0)
	var t models.Tag
	switch table {
	case 1:
		t = new(models.ZBTag)
	case 2:
		t = new(models.Category)
	default:
		log.Println("please set table value in config file")
		os.Exit(1)
	}
	tagID := InsertRootTag(t)
	InsertJson(t, f, tagID, tagType)
}

// InsertRootTag 插入根节点
func InsertRootTag(t models.Tag) int64 {
	section, err := cfg.GetSection("data")
	if err != nil {
		log.Println("get root tag info error, please check your config file")
		os.Exit(1)
	}
	rootTagName := section.Key("root_tag_name").String()
	parentID := section.Key("root_tag_parent_id").MustInt64(0)
	if rootTagName == "" {
		return parentID
	}
	tagID := t.InsertTag(section.Key("root_tag_name").String(), section.Key("root_tag_parent_id").MustInt64(), tagType, false)
	return tagID
}

// func foreachJson(aa interface{}, p int64) {
// 	m := aa.(map[string]interface{})
// 	relation := ""
// 	for k, v := range m {
// 		temp := insert(k, 65, true)
// 		fmt.Println("insert id ", temp.Id)
// 		relation = relation + fmt.Sprintf("%d,", temp.Id)
// 		switch vv := v.(type) {
// 		case string:
// 			fmt.Println(k, "is string", vv)
// 		case int:
// 			fmt.Println(k, "is int", vv)
// 		case float64:
// 			fmt.Println(k, "is float64", vv)
// 		case []interface{}:
// 			fmt.Println(k, "is an array:")
// 			rr := ""
// 			for i, u := range vv {
// 				fmt.Println(i, u)
// 				tt := insert(fmt.Sprintf("%s", u), 76, false)
// 				rr += fmt.Sprintf("%d,", tt.Id)
// 			}
// 			update(temp.Id, rr)
// 		case map[string]interface{}:
// 			fmt.Println(k, "is an map:")
// 			foreachJson(v.(map[string]interface{}), int64(temp.Id))
// 		default:
// 			fmt.Println(k, "is of a type I don't know how to handle")
// 		}
// 	}
// 	update(p, relation)
// }
